package com.turtledove.storyalbum.control;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ProgressBar;
import android.widget.ViewFlipper;

import com.facebook.LoggingBehavior;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.Settings;
import com.turtledove.storyalbum.R;
import com.turtledove.storyalbum.common.ConstCommon;
import com.turtledove.storyalbum.model.adapter.AdapterFacebookAlbum;
import com.turtledove.storyalbum.model.delegate.ServiceDelegate;
import com.turtledove.storyalbum.model.object.ObjectFacebookAlbum;
import com.turtledove.storyalbum.model.object.ObjectFacebookImage;

public class FacebookAlbumUpdateActivity extends Activity {

	GridView gridContent;
	AdapterFacebookAlbum adapter;
	ArrayList<ObjectFacebookAlbum> arrayAlbum;
	ArrayList<ObjectFacebookImage> arrayImage;
	Context mContext;
	int CREATE_NEW_ALBUM = 1, UPDATE_ALBUM = 2;
	String KEY_FROM_WHERE;
	int KEY_ID_ALBUM;

	int LOADING = 0, CONTENT = 1, ERRO = 2;
	ViewFlipper vf;
	ProgressBar progressBar;

	// for facebook
	String access_token;
	Session.StatusCallback statusCallback = new SessionStatusCallback();
	Bundle mSavedInstanceState;
	List<String> listPermission = Arrays.asList("user_photos");
	Session mSession;
	int FACE_CODE = 100;
	int idAlbum;
	// __________________________ System Function

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mSavedInstanceState = savedInstanceState;
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_facebook_album);
		mContext = this;
		initDB();
		initWidget();
		loginToFacebook();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == UPDATE_ALBUM) {
			if (resultCode == RESULT_OK) {
				Intent returnIntent = new Intent();
				returnIntent.putExtra(ConstCommon.KEY_RESULT_ID_ALBUM, idAlbum);
				setResult(RESULT_OK, returnIntent);
				finish();
			}
		} 
		
		Session.getActiveSession().onActivityResult(this, requestCode,
				resultCode, data);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mSession = Session.getActiveSession();
		Session.saveSession(mSession, outState);
	}
	
	//request Permissions
	Session.OpenRequest requestPermission()
	{
		Session.OpenRequest requestPermissions = new Session.OpenRequest(FacebookAlbumUpdateActivity.this);
		requestPermissions.setPermissions(listPermission);
		requestPermissions.setCallback(statusCallback);
		requestPermissions.setRequestCode(FACE_CODE);
		return requestPermissions;
	}
	
	// login facebook
	private void loginToFacebook() {
		try {
			Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
			Session session = Session.getActiveSession();
			if (session == null) {
				if (mSavedInstanceState != null) {
					session = Session.restoreSession(this, null, statusCallback,
							mSavedInstanceState);
				}
				if (session == null) {
					session = new Session(this);
				}
				session.openForPublish(requestPermission());
				Session.openActiveSession(FacebookAlbumUpdateActivity.this, true, listPermission, statusCallback);
			}
			updateViewFacebook();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	@SuppressLint("HandlerLeak")
	private void updateViewFacebook() {
		try {
			Session session = Session.getActiveSession();
			if (session.isOpened()) {
				if (access_token == null) {
					access_token = session.getAccessToken();
					progressBar.setVisibility(View.VISIBLE);
					ServiceDelegate.getFacebookAlbum(mhandler, access_token);
				}
			} else {
				if (!session.isOpened() && !session.isClosed()) {
					session.openForPublish(requestPermission());
				} else {
					Session.openActiveSession(FacebookAlbumUpdateActivity.this, true, listPermission, statusCallback);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	class SessionStatusCallback implements Session.StatusCallback {
		@Override
		public void call(Session session, SessionState state,
				Exception exception) {
			updateViewFacebook();
		}
	}

	//

	private void initWidget() {
		vf = (ViewFlipper) findViewById(R.id.vf);
		vf.setDisplayedChild(LOADING);
		progressBar = (ProgressBar) vf.findViewById(R.id.progressBar);
		progressBar.setVisibility(View.GONE);
	}

	private void initDB() {
		Intent intent = new Intent();
		intent = getIntent();
		idAlbum = intent.getExtras().getInt(ConstCommon.KEY_FROM_WHERE_ITEM_ID_ALBUM);
		arrayAlbum = new ArrayList<ObjectFacebookAlbum>();
	}

	Handler mhandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.arg1 == 0) {
				try {

					arrayAlbum = new ArrayList<ObjectFacebookAlbum>();
					JSONObject dataJSONObject = new JSONObject();
					dataJSONObject = (JSONObject) msg.obj;

					JSONArray dataJSONArray = new JSONArray();
					Log.d("Luong", "==================== json album: "
							+ dataJSONArray);
					dataJSONArray = dataJSONObject
							.getJSONArray(ServiceDelegate.KEY_DATA);
					int totalAlbum = dataJSONArray.length();
					if (totalAlbum > 0) {
						for (int i = 0; i < totalAlbum; i++) {
							JSONObject albumJSONObject = new JSONObject();
							albumJSONObject = dataJSONArray.getJSONObject(i);
							int totalImage = -1;
							try {
								totalImage = albumJSONObject
										.getInt(ServiceDelegate.KEY_COUNT);
							} catch (Exception e) {
								// TODO: handle exception
							}
							if (totalImage > 0) {
								if (totalImage > 0) {
									ObjectFacebookAlbum mObjectFacebookAlbum = new ObjectFacebookAlbum();
									String idAlbum = albumJSONObject
											.getString(ServiceDelegate.KEY_ID);
									mObjectFacebookAlbum.setAlbum_id(idAlbum);
									mObjectFacebookAlbum
											.setAlbum_name(albumJSONObject
													.getString(ServiceDelegate.KEY_NAME));
									arrayAlbum.add(mObjectFacebookAlbum);
								}
							}

						}
						if (arrayAlbum.size() > 0) {
							vf.setDisplayedChild(CONTENT);
							gridContent = (GridView) vf
									.findViewById(R.id.gridContent);
							gridContent.setFastScrollEnabled(true);
							adapter = new AdapterFacebookAlbum(
									FacebookAlbumUpdateActivity.this, arrayAlbum);
							gridContent.setAdapter(adapter);
							gridContent
									.setOnItemClickListener(new OnItemClickListener() {

										@Override
										public void onItemClick(
												AdapterView<?> parent,
												View view, int position, long id) {
											Intent intent = new Intent(
													mContext,
													FacebookImageUpdateActivity.class);
											intent.putExtra(
													ConstCommon.KEY_RESULT_ID_ALBUM,
													arrayAlbum.get(position).getAlbum_id());
											intent.putExtra(ServiceDelegate.KEY_ACCESS_TOKEN,access_token);
											intent.putExtra(ServiceDelegate.KEY_ID,idAlbum);
											startActivityForResult(intent,UPDATE_ALBUM);
										}
									});

						} else {
							vf.setDisplayedChild(ERRO);
						}
					} else {
						vf.setDisplayedChild(ERRO);
					}

				} catch (Exception e) {
					vf.setDisplayedChild(ERRO);
				}
			} else {
				vf.setDisplayedChild(ERRO);
			}
		}
	};
}
